Page({
  data: {
    activity: {
      id: '',
      title: '',
      description: '',
      coverUrl: '',
      timeRange: '',
      voteLimit: 1,
      participantCount: 0,
      totalVotes: 0,
      countdown: 0,
      status: 'ongoing'
    },
    candidates: [] as any[],
    topCandidates: [] as any[],
    userInfo: null as any
  },

  onLoad(options: any) {
    // 获取活动ID
    const activityId = options.id
    console.log('活动ID:', activityId)
    
    if (!activityId) {
      wx.showToast({
        title: '活动ID不存在',
        icon: 'none'
      })
      wx.navigateBack()
      return
    }
    
    // 获取用户信息
    const userInfo = wx.getStorageSync('userInfo')
    this.setData({
      userInfo: userInfo
    })
    
    // 清空初始的模拟数据
    this.setData({
      activity: {
        id: '',
        title: '',
        description: '',
        coverUrl: '',
        timeRange: '',
        voteLimit: 1,
        participantCount: 0,
        totalVotes: 0,
        countdown: 0,
        status: 'ongoing'
      },
      candidates: [],
      topCandidates: []
    })
    
    // 获取活动详情和选手列表
    this.getActivityDetail(activityId)
  },

  onShow() {
    // 更新排行榜
    this.updateRanking()
    
    // 重新检查用户信息
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.setData({ userInfo })
    }
  },

  // 获取活动详情
  async getActivityDetail(activityId: string) {
    try {
      wx.showLoading({
        title: '加载中...'
      })
      
      const result = await wx.cloud.callFunction({
        name: 'activityManager',
        data: {
          action: 'getDetail',
          activityId: activityId
        }
      })
      
      wx.hideLoading()
      
      const response = result.result as any
      if (response && response.success) {
        const activityData = response.data.activity || response.data
        const candidatesData = response.data.candidates || []
        
        console.log('云函数返回的原始活动数据:', activityData)
        console.log('云函数返回的原始候选人数据:', candidatesData)
        
        // 格式化时间显示
        let timeRange = ''
        let countdown = 0
        
        if (activityData.startTime && activityData.endTime) {
          const startDate = new Date(activityData.startTime)
          const endDate = new Date(activityData.endTime)
          const now = new Date()
          
          // 格式化时间范围
          const formatDate = (date: Date) => {
            const year = date.getFullYear()
            const month = date.getMonth() + 1
            const day = date.getDate()
            return `${year}.${month}.${day}`
          }
          
          timeRange = `${formatDate(startDate)}-${formatDate(endDate)}`
          
          // 计算倒计时（距离结束还有多少天）
          const timeDiff = endDate.getTime() - now.getTime()
          countdown = Math.max(0, Math.ceil(timeDiff / (1000 * 60 * 60 * 24)))
        }
        
        // 处理活动数据
        const activity = {
          id: activityData._id || activityId,
          title: activityData.title || '未命名活动',
          description: activityData.description || '',
          coverUrl: activityData.coverUrl || '',
          timeRange: timeRange,
          voteLimit: activityData.voteLimit || 1,
          participantCount: activityData.participantCount || 0,
          totalVotes: activityData.totalVotes || 0,
          countdown: countdown,
          status: activityData.status || 'ongoing'
        }
        
        // 处理候选人数据
        const candidates = candidatesData.map((candidate: any) => ({
          id: candidate._id,
          name: candidate.name || '未命名候选人',
          imageUrl: candidate.images && candidate.images.length > 0 ? candidate.images[0] : '',
          shortDescription: candidate.description ? 
            (candidate.description.length > 10 ? 
              candidate.description.substring(0, 10) + '...' : 
              candidate.description) : '',
          votes: candidate.votes || 0
        }))
        
        this.setData({
          activity: activity,
          candidates: candidates
        })
        
        // 更新排行榜
        this.updateRanking()
        
        console.log('获取活动详情成功:', activity)
        console.log('获取选手列表成功:', candidates)
      } else {
        console.log('获取活动详情失败:', response?.message)
        wx.showToast({
          title: response?.message || '获取活动详情失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('获取活动详情失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: '网络错误',
        icon: 'none',
        duration: 2000
      })
    }
  },

  // 更新排行榜
  updateRanking() {
    const sortedCandidates = [...this.data.candidates].sort((a, b) => b.votes - a.votes)
    this.setData({
      topCandidates: sortedCandidates
    })
  },

  // 返回上一页
  goBack() {
    wx.navigateBack()
  },

  // 跳转到选手详情页
  goToCandidateDetail(e: any) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/candidate/detail/index?id=${id}&activityId=${this.data.activity.id}`
    })
  }
}) 